package com.example.onlinemonitoring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.FileUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

@Api(value = "模板引擎", tags = { "模板引擎" })
@Controller
@RequestMapping("/freemarker")
public class Freemarker {
    @ApiOperation(value = "创建数据库", notes = "创建数据库")
    @RequestMapping(value = "/updateAlarm", method = RequestMethod.POST)
    public String test(HttpServletRequest request, Model model) {
        String template1 = request.getParameter("template1");
        String template2 = request.getParameter("template2");
        template2 = template2.replace("/>", "/&gt;");
        String selectedfun = request.getParameter("selectedfun");
        if (template1.equals("")) {
            return "blankpage";
        }
        String path;
        try {
            path = new ClassPathResource("/template/tmp61850.ftl").getURL().getPath();
            File file = new File(path);
            System.out.println(file.getPath() + " exists -> " + file.exists());
            String filepath = file.getPath();
            FileUtil.writeFile(filepath, template2);
            JSONObject object = JSONObject.parseObject(template1);
            model.addAttribute("demo", object);
        } catch (IOException e) {
            e.printStackTrace();
        }
        switch (selectedfun) {
            case "自动生成创建数据库语句":
                return "createdatabasefmres";
            case "自动生成comCenter":
                return "comCenter2";
            case "自动生成61850模板":
                return "tmp61850";
            default:
                return "blankpage";
        }
    }

    @GetMapping("/index")
    public String index() {
        return "freemarker";
    }
}
